/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package p2_nb;

import java.awt.Point;
import java.sql.*;
import java.util.Random;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author student
 */
public class Main
{
    static Connection con;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
        try
        {
            Class.forName("org.postgresql.Driver");
        }catch( ClassNotFoundException e)
        {   
        }
        String url = "jdbc:postgresql://localhost:5432/postgis";
        try
        {
            con = DriverManager.getConnection(url, "postgres", "hda");
            con.setAutoCommit(false);
            System.out.println("Datenbank verbunden!");
        } catch (SQLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        insertRandomData();
        printTableData();

        try {
            con.close();
        } catch (SQLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    static public void printTableData()
    {
        String cmd = "SELECT ST_AsText(geo) AS geo FROM GeoDbLand";
        Statement s;
        try
        {
            s = con.createStatement();
            ResultSet rs = s.executeQuery(cmd);
            con.commit();
            while(rs.next())
            {
                System.out.println("Geo: "+rs.getString("geo"));
            }
        } catch (SQLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    static public void insertRandomData()
    {
        String cmd = "";

        for(int k=0; k < 10; k++)
        {
            cmd = "INSERT INTO GeoDbLand (id,geo) VALUES ("+(k+1)+",ST_PolygonFromText('POLYGON((";
            Vector<Point> v1 = createRandomPoly();
            for(int j=0; j < v1.size(); j++)
            {
                cmd += v1.elementAt(j).x+" "+v1.elementAt(j).y;
                if( j != v1.size()-1) cmd += ",";
            }
            cmd += "))', -1));";
            System.out.println("QUERY: "+cmd);
            try
            {
                Statement s = con.createStatement();
                s.execute(cmd);
                con.commit();
            } catch (SQLException ex)
            {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    static public Vector<Point> createRandomPoly()
    {
        Vector<Point> v = new Vector<Point>();
        Random r = new Random();
        int ind = r.nextInt(15)+5;

        for(int i=0; i < ind; i++)
        {
            v.add(new Point(r.nextInt(100), r.nextInt(100)));
        }

        v.add(v.elementAt(0));

        return v;
    }

}
